package com.voicenews.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Html;
import android.util.Log;

import com.voicenews.model.Article;

public class Utils {
	
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	private final static String BOLD_OPEN = "<B>";
	private final static String BOLD_CLOSE = "</B>";
	private final static String BREAK = "<BR>";
	private final static String ITALIC_OPEN = "<I>";
	private final static String ITALIC_CLOSE = "</I>";
	private final static String SMALL_OPEN = "<SMALL>";
	private final static String SMALL_CLOSE = "</SMALL>";

	/**
	 * This method takes a list of Article objects and converts them in to the
	 * correct JSON format so the info can be processed by our list view
	 * 
	 * @param articles
	 *            - list<Article>
	 * @return List<JSONObject> - suitable for the List View activity
	 */
	public static List<JSONObject> fillData(List<Article> articles) {

		List<JSONObject> items = new ArrayList<JSONObject>();
		for (Article article : articles) {
			JSONObject current = new JSONObject();
			try {
				buildJsonObject(article, current);
			} catch (JSONException e) {
				Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
			}
			items.add(current);
		}

		return items;
	}

	/**
	 * This method takes a single Article Object and converts it in to a single
	 * JSON object including some additional HTML formating so they can be
	 * displayed nicely
	 * 
	 * @param article
	 * @param current
	 * @throws JSONException
	 */
	private static void buildJsonObject(Article article, JSONObject current)
			throws JSONException {
		String title = article.getTitle();
		String description = article.getDescription();
		String date = article.getPubDate();
		String imgLink = article.getImgLink();

		StringBuffer sb = new StringBuffer();
		sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
		sb.append(BREAK);
		sb.append(description);
		sb.append(BREAK);
		sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date)
				.append(ITALIC_CLOSE).append(SMALL_CLOSE);

		current.put("text", Html.fromHtml(sb.toString()));
		current.put("imageLink", imgLink);
		current.put("link", article.getUrl());
		current.put("title", article.getTitle());
	}

	public static List<JSONObject> convertToJSONObjects(String response) {
		JSONObject jso;
		List<JSONObject> result = new ArrayList<JSONObject>();
		try {
			jso = new JSONObject(response);

			JSONArray ja = jso.optJSONArray("article");
			if (ja != null) {
				for (int i = 0; i < ja.length(); i++) {
					JSONObject jsonMsg = ja.getJSONObject(i);
					JSONObject current = new JSONObject();
					StringBuffer sb = new StringBuffer();
					Object pubDate = jsonMsg.opt("pubDate");
					if (pubDate != null) {
						pubDate = new Date(Long.valueOf(pubDate.toString()))
								.toString();
					} else {
						pubDate = "";
					}
					sb.append(BOLD_OPEN).append(jsonMsg.optString("title"))
							.append(BOLD_CLOSE);
					sb.append(BREAK);
					sb.append(jsonMsg.optString("description"));
					sb.append(BREAK);
					sb.append(SMALL_OPEN).append(ITALIC_OPEN)
							.append(pubDate.toString()).append(ITALIC_CLOSE)
							.append(SMALL_CLOSE);
					current.put("text", Html.fromHtml(sb.toString()));
					if (jsonMsg.opt("imgLink") != null) {
						current.put("imageLink", jsonMsg.getString("imgLink"));
					} else {
						current.put("imageLink", "");
					}

					current.put("url", new URL(jsonMsg.getString("url")));
					current.put("title", jsonMsg.getString("title"));
					current.put("articleId", jsonMsg.getString("articleId"));
					result.add(current);
				}

			} else {
				JSONObject jsonMsg = jso.getJSONObject("article");
				JSONObject current = new JSONObject();
				StringBuffer sb = new StringBuffer();
				sb.append(BOLD_OPEN).append(jsonMsg.getString("title"))
						.append(BOLD_CLOSE);
				sb.append(BREAK);
				sb.append(jsonMsg.getString("description"));
				sb.append(BREAK);
				sb.append(SMALL_OPEN)
						.append(ITALIC_OPEN)
						.append(new Date(Long.valueOf(jsonMsg
								.getString("pubDate")))).append(ITALIC_CLOSE)
						.append(SMALL_CLOSE);
				current.put("text", Html.fromHtml(sb.toString()));
				if (jsonMsg.opt("imgLink") != null) {
					current.put("imageLink", jsonMsg.getString("imgLink"));
				} else {
					current.put("imageLink", "");
				}

				current.put("link", new URL(jsonMsg.getString("url")));
				current.put("title", jsonMsg.getString("title"));
				result.add(current);

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		// if no network is available networkInfo will be null
		// otherwise check if we are connected
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

}